package com.sljy.hzk.ui.task;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.api.InjectParam;
import com.google.gson.Gson;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.entity.HiddenDangerDetalisEntity;
import com.sljy.hzk.entity.TaskDatabaseEntity;
import com.sljy.hzk.entity.TaskDetailEntity;
import com.sljy.hzk.net.CommonResult;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.TaskService;
import com.sljy.hzk.util.picture.TakePictureUtils;
import com.sljy.hzk.view.CustomStateText;
import com.sljy.hzk.view.adapter.ChosePicAdapter;
import com.tkk.api.RxEventProcessor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@ActivityInfo(layout = R.layout.activity_hidden_danger, isShowActionBar = true, title = "隐患排查",rightIcRes = R.drawable.homepage )
public class HiddenDangerActivity extends BaseActivity {
    @InjectParam
    public int dangerId;
    @InjectParam
    boolean isFinish = false;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_partition_info)
    TextView tvPartitionInfo;
    @BindView(R.id.tv_up)
    Button tvUp;
    @BindView(R.id.img_bg)
    ImageView imgBg;
    @BindView(R.id.aaa)
    TextView tvOne;
    @BindView(R.id.bbb)
    TextView bbb;
    @BindView(R.id.tv_plan)
    TextView tvPlan;
    @BindView(R.id.edit)
    EditText edit;
    @BindView(R.id.recycer)
    RecyclerView recycerPic;
    @BindView(R.id.addPic)
    TextView addPic;
    ChosePicAdapter chosePicAdapter;
    List<String> picUrl = new ArrayList<>();//已经选择的图片--网络地址
    List<String> picPaths = new ArrayList<>();
    public TakePictureUtils takePictureUtils;

    @Override
    protected void init() {
        HiddenDangerActivity__JumpCenter.bind(this);
        addPic.setVisibility(View.GONE);
        if(isFinish)
            tvUp.setVisibility(View.GONE);
        chosePicAdapter = new ChosePicAdapter(this, picPaths,3);
        chosePicAdapter.setListener(() -> showPhotoDialog());
        chosePicAdapter.hideTvAdd();
        addPic.setOnClickListener( new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                chosePicAdapter.OnTvAddClick();
            }
        });
        recycerPic.setLayoutManager(new GridLayoutManager(this, 3));
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override public void successful(File outFile) {
                showPic(outFile.getPath());
            }
            @Override public void failed(int errorCode, List<String> deniedPermissions) { }
        });
        recycerPic.setAdapter(chosePicAdapter);
        HttpHeper.get().create(TaskService.class)
                .getHiddenDanger(dangerId)
                .compose(getThread())
                .compose(this.bindToLifecycle())
                .subscribe(new BaseCallBack<HiddenDangerDetalisEntity>(this) {
                    @Override
                    public void onCallBackSuccess(HiddenDangerDetalisEntity data) {
                        tvTitle.setText(data.getTitle());
                        tvPartitionInfo.setText(data.getPartition());
                        imgBg.setVisibility(TextUtils.isEmpty(data.getPlan()) ? View.VISIBLE : View.GONE);
                        tvOne.setVisibility(!TextUtils.isEmpty(data.getPlan()) ? View.VISIBLE : View.GONE);
                        tvPlan.setText(data.getPlan());
                    }
                });
    }
    private void showPic(String path) {
        picPaths.add(path);
        chosePicAdapter.notifyItemInserted(picPaths.size() );
    }

    @Override
    protected boolean isShouldHideInput(View v, MotionEvent event) {
        return false;
    }

    @OnClick(R.id.tv_up)
    void up() {
        String result = edit.getText().toString();
        if (TextUtils.isEmpty(result)){
            showToast("请填写完成情况");
            return;
        }
        upPic(result);
   }
    //上传隐患
   private void sendData( String result){
       if(picUrl.size() != picPaths.size())return;
       Gson gson = new Gson();
       HttpHeper.get().create(TaskService.class)
           .submitHiddenDanger(dangerId, result, gson.toJson(picUrl),"username")
           .compose(getThread())
           .compose(this.bindToLifecycle())
           .subscribe(new BaseCallBack<Object>(this) {
               @Override
               public void onCallBackSuccess(Object data) {
                   RxEventProcessor.get().post("dataHaveChange");
                   showToast("上传成功",R.drawable.uploadsuccess);
                   finish();
               }
           });
   }

    //上传图片并且赋值
    public void upPic( String result){
        picUrl.clear();
        for (int i = 0; i < picPaths.size(); i++) {
            File file = new File(picPaths.get(i));
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part requestImgPart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            Call<CommonResult<String>> data = HttpHeper.get().create(TaskService.class).upPicture(requestImgPart);
            data.enqueue( new Callback <CommonResult<String>>(){
                @Override
                public void onResponse(Call<CommonResult<String>> call, Response<CommonResult<String>> response) {
                    if(response.isSuccessful()){
                        picUrl.add(response.body().getData());
                        Log.i(TAG,"上传成功啦"+response.body().getData());
                        sendData(result);
                    }else {
                        showToast("上传失败");
                    }
                }
                @Override
                public void onFailure(Call<CommonResult<String>> call, Throwable t) {
                    showToast("上传失败");
                }
            });
        }
    }
    public void showPhotoDialog() {
        new MaterialDialog.Builder(this)
                .items("选择本地照片", "拍照")
                .itemsCallback((dialog, itemView, position, text) -> {
                    switch (position) {
                        case 0: // 选择本地照片
                            takePictureUtils.getByAlbum();
                            break;
                        case 1: // 拍照
                            takePictureUtils.getByCarema();
                            break;
                    }
                }).show();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
